package com.yanghui.dtracing.boot;

import com.yanghui.dtracing.core.utils.AgentPackagePath;

import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

public class Version {

    public static String getVersion() {
        JarFile myJarFile = null;
        try {
            String file = AgentPackagePath.getPath() + "/dtracing-boot.jar";
            myJarFile = new JarFile(file);
            Enumeration myEnum = myJarFile.entries();
            Manifest manifest = null;
            while(myEnum.hasMoreElements()){
                JarEntry myJarEntry = (JarEntry)myEnum.nextElement();
                if(myJarEntry.getName().contains("MANIFEST.MF")){
                    manifest = new Manifest(myJarFile.getInputStream(myJarEntry));
                    break;
                }
            }
            Attributes attributes = manifest.getMainAttributes();
            String version = attributes.getValue("Implementation-Version");
            if(null == version || "".equalsIgnoreCase(version)){
                return "未agent获取到版本号";
            }
            return version;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "获取版本异常";
        }finally {
            try{
                if(null != myJarFile){
                    myJarFile.close();
                }
            }catch (Exception e){
                //ignore
            }
        }
    }
}
